package com.example.cxf.service.listener;

import com.example.cxf.annotation.RestService;
import org.apache.cxf.Bus;
import org.apache.cxf.jaxrs.JAXRSServerFactoryBean;
import org.apache.cxf.jaxrs.lifecycle.SingletonResourceProvider;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

import java.util.Map;

@Component
public class CxfRestWebServiceListener implements ApplicationContextAware, ApplicationListener<ContextRefreshedEvent> {

    private ApplicationContext applicationContext;

    @Autowired
    private Bus bus;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
        Map<String, Object> beansWithAnnotation = applicationContext.getBeansWithAnnotation(RestService.class);
        for (Map.Entry<String, Object> entry : beansWithAnnotation.entrySet()) {
            JAXRSServerFactoryBean jaxrsServerFactoryBean = new JAXRSServerFactoryBean();
            jaxrsServerFactoryBean.setBus(bus);
            jaxrsServerFactoryBean.setAddress("/" + entry.getKey());
            jaxrsServerFactoryBean.setResourceProvider(new SingletonResourceProvider(entry.getValue()));
            jaxrsServerFactoryBean.setResourceClasses(entry.getValue().getClass());
            jaxrsServerFactoryBean.create();
        }
    }
}

